using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LCL.Caching;
using LCL.LData;
using System.Data;
using System.Diagnostics;

namespace LCL.DbObjects.MySQL
{
    [Serializable]
    [DebuggerDisplay("{ConnectionString}")]
    public class DbObject : DbModelBase, IDbObject
    {
        public List<DataBaseModel> GetDBList(string host)
        {
            if (string.IsNullOrWhiteSpace(host)) return new List<DataBaseModel>();
            string cacheKey = string.Format(CacheKey_DBLIST, host);
            return cache.Get(cacheKey, () =>
            {
                List<DataBaseModel> dbmList = new List<DataBaseModel>();
                var dt = DbHelper.ExecuteDataTable("show databases", null);
                foreach (DataRow row in dt.Rows)
                {
                    string dbName = row["Database"].ToString();
                    DataBaseModel dbm = new DataBaseModel();
                    dbm.DatabaseName = dbName;
                    dbmList.Add(dbm);
                }
                return dbmList;
            });
        }
        public List<TableModel> GetTables(string dbName, bool iscol = false)
        {
            if (string.IsNullOrWhiteSpace(dbName)) return new List<TableModel>();
            string cacheKey = string.Format(CacheKey_TABLELIST, dbName);
            return cache.Get(cacheKey, () =>
            {
                var list = new List<TableModel>();
                var dt = DbHelper.ExecuteDataTable(@"SELECT table_name ,table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_type='base table'
and table_schema = '" + dbName + "' order by table_name asc ", null);
                foreach (DataRow row in dt.Rows)
                {
                    var tm = new TableModel();
                    string name = row["table_name"].ToString();
                    string remark = row["table_comment"].ToString();
                    if (!string.IsNullOrWhiteSpace(remark))
                    {
                        string[] tremp = remark.Split(';');
                        if (tremp.Length > 0)
                        {
                            tm.TableNameRemark = tremp[0];
                        }
                        else
                        {
                            tm.TableNameRemark = remark;
                        }
                    }
                    else
                    {
                        tm.TableNameRemark = name;
                    }
                    tm.TableName = name;
                    if (iscol)
                    {
                        if (tm.Columns == null || tm.Columns.Count == 0)
                        {
                            tm.Columns = GetColumnInfoList(dbName, name);
                        }
                    }

                    list.Add(tm);
                }
                return list;
            });
        }
        public List<TableColumn> GetColumnInfoList(string dbName, string tableName)
        {
            if (string.IsNullOrWhiteSpace(dbName) || string.IsNullOrWhiteSpace(tableName)) return null;
            string cacheKey = string.Format(CacheKey_TABLE_COL, dbName, tableName);
            return cache.Get(cacheKey, () =>
            {
                #region MyRegion
                var list = new List<TableColumn>();
                var dt = DbHelper.ExecuteDataTable("use " + dbName + "; show full fields from " + tableName + " ;", null);
                int colder = 1;
                foreach (DataRow row in dt.Rows)
                {
                    var tc = new TableColumn();
                    tc.ColumnOrder = colder;
                    tc.ColumnName = row["Field"].ToString();
                    tc.ColumnRemark = row["Comment"].ToString();
                    tc.ColumnType = row["Type"].ToString();
                    tc.DefaultValue = row["Default"].ToString();
                    if (row["Key"].ToString() == "PRI")
                    {
                        tc.IsPrimaryKey = true;
                    }
                    if (row["Null"].ToString() == "YES")
                    {
                        tc.IsNullable = true;
                    }
                    if (row["Extra"].ToString() == "auto_increment")
                    {
                        tc.IsIdentity = true;
                    }
                    string typeName = tc.ColumnType;
                    string length = "";
                    string precision = "";
                    string scale = "";
                    this.TypeNameProcess(tc.ColumnType, out typeName, out length, out precision, out scale);
                    tc.ColumnType = typeName;
                    tc.MaxLength = Utils.GetObjTranNull<int>(length);

                    list.Add(tc);
                    colder++;
                }
                return list;
                #endregion
            });
        }
        public List<TableRelation> GetTableRelation(string tableName)
        {
            return new List<TableRelation>();
        }
        public void AddTableByKey(string dbName)
        {

        }
        public void ExtendedProperty(bool addbyupdate, string describe, string tableName, string columnName)
        {
            if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentException("tableName");
            if (string.IsNullOrWhiteSpace(describe)) throw new ArgumentException("describe");

            string sql_propertyInfo = @"alter table {0} comment='{1}'";//修改表的注释
            string sql_propertyInfo1 = @"alter table {0} modify column {1} int comment '{2}'";//修改字段的注释
            string sql = "";
            if (string.IsNullOrWhiteSpace(columnName))
            {//修改表
                sql = string.Format(sql_propertyInfo, tableName, describe);
            }
            else
            {
                sql = string.Format(sql_propertyInfo1, tableName, columnName, describe);
            }

            DbHelper.ExecuteNonQuery(sql, null);
            string cacheKey = CacheKey_TABLE_COL + tableName;
            cache.Remove(cacheKey);
        }
        public TableModel GetTableInfo(string dbName, string tableName)
        {
            if (string.IsNullOrWhiteSpace(dbName) || string.IsNullOrWhiteSpace(tableName)) return null;
            string cacheKey = string.Format(CacheKey_TABLE_INFO, dbName, tableName);
            return cache.Get(cacheKey, () =>
            {
                var tables = this.GetTables(dbName);
                TableModel tm = tables.FirstOrDefault(p => p.TableName == tableName);
                if (tm.Columns == null || tm.Columns.Count == 0)
                {
                    tm.Columns = GetColumnInfoList(dbName, tableName);
                }
                return tm;
            });
        }


    }
}
